﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using MongoDB.Bson;
using MongoDB.Driver;
using Elasticsearch.Synchronize.Domain.Events;
using Elasticsearch.Synchronize.Domain.Interface;

namespace Elasticsearch.Synchronize.DomainEventHandler.Handler
{
    public class GetRuleDataEventHandler : MediatR.NotificationHandler<GetRuleDataDomainEvent>
    {
        private readonly ISynchronizeItemRepository _itemRepository;

        public GetRuleDataEventHandler(ISynchronizeItemRepository itemRepository)
        {
            _itemRepository = itemRepository;
        }

        protected override void HandleCore(GetRuleDataDomainEvent notification)
        {
            var rule = notification.SynchronizeRule;

            var mongoClient = new MongoClient(rule.RuleMongoServerUrl);
            var mongoDatabase = mongoClient.GetDatabase(rule.RuleMongoDatabase);
            var mongoCollection = mongoDatabase.GetCollection<BsonDocument>(rule.RuleMongoCollection);
            var filter = new JsonFilterDefinition<BsonDocument>(rule.RuleFilter);
            var projection = Builders<BsonDocument>.Projection.ToBsonDocument();
            if (rule.RuleProjection != null && rule.RuleProjection.Any())
            {
                foreach (var project in rule.RuleProjection)
                {
                    projection.Set(project, 1);
                }
            }

            var ruleData = mongoCollection.Find(filter).Project(projection).ToList();
            rule.RuleDataList = ruleData;

            rule.RuleItemList = _itemRepository.GetItemsByRuleId(rule.Identity);

            rule.TraverseRuleData();
        }
    }
}